package com.fy.aop;

import cn.hutool.json.JSONUtil;
import com.fy.entity.Log;
import com.fy.entity.User;
import com.fy.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Aspect
public class MyLog {
    @Autowired
    ILogService logService;
    @Autowired
    HttpServletRequest request;
    @Before("@annotation(com.fy.aop.LogAnn)")
    public void log(JoinPoint joinPoint) throws InterruptedException {
        System.out.println("前置通知开始-----------------------");
        Log log = new Log();
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof User){
            log.setUsername(((User) principal).getUsername());
        }else{
            log.setUsername("匿名用户");
        }
        log.setFrmid(request.getRemoteAddr());
        log.setUrl(request.getRequestURI());
        Object[] args = joinPoint.getArgs();
        String s = JSONUtil.toJsonStr(args);
        log.setArgs(s);
        log.setTime(LocalDateTime.now());
        logService.saveAop(log);
        System.out.println("前置通知结束-----------------------");
    }
}
